const extension = chrome.extension;
const port = extension.connect();
var isOn;
var isLoaded = false;
var numArticles = 0;
var tagMap = {};
var aTag = new Array();
var aTitle = new Array();
var aArtist = new Array();
var aLink = new Array();
var aIntro = new Array();
var aImage = new Array();
var aLocalEventShortMonth = new Array();
var aLocalEventDay = new Array();
var aLocalEventShortWeekday = new Array();
var aDatePublished = new Array();
var aVenueName = new Array();

var respRss;
var tabID;

listenToState(port);
port.postMessage({});

function listenToState(port){
    port.onMessage.addListener(function(data){
        isOn = data.isOn;
        isLoaded = (data.respRSS != undefined);
        tagMap = {};
        if (isOn) {
            if (!isLoaded) {
                loadTags();
            }
            else {
                if (aTag.length == 0) 
                    loadRSSResponse(data.respRSS);
            }
        }
        highlightAll(isOn);
    });
}


function highlightAll(bHightlight){
    var idCSS;
    $.each(aTag, function(i, objValue){
        try {
            idCSS = 'jQueryLinkTM' + i;
            if (bHightlight) {
                if ($('body a.' + idCSS).size() == 0) {
                    $("body").highlight(objValue, {
                        element: 'a',
                        className: idCSS,
                        wordsOnly: true
                    });
                    $("." + idCSS).css({
                        backgroundColor: "#004477",
                        color: "#ffffff",
                        padding: "0 25px 0 2px",
                        backgroundImage: "url(http://gce-tm.googlecode.com/svn/trunk/icon.png)",
                        backgroundRepeat: "no-repeat",
                        backgroundPosition: "right center"
                    });
                    $('body a.' + idCSS).qtipTM({
                        content: '<h1 class=\'logoTM\'><img src=\'http://gce-tm.googlecode.com/svn/trunk/img/logo-ticket.gif\' alt=\'TicketMaster\'/></h1><div class=\'contenidosTM\'><div class=\'izq\'><div class=\'dch\'><img src=\'' + aImage[i] + '\' alt=\'\' width=\'95\' height=\'60\' border=\'0\' class=\'mainTM\'/><div class=\'bloqueTM\'><span class=\'antetitulo\'>' + aArtist[i] + '</span><span class=\'titulo\'>' + aTitle[i] + '</span><div class=\'eventoTM\'><span class=\'h6\'>Next Event</span><div class=\'fecha\'>-' + aLocalEventShortMonth[i] + '-<br /><span class=\'num\'>' + aLocalEventDay[i] + '</span><br /><strong>' + aLocalEventShortWeekday[i] + '</strong></div><div class=\'lugarTM\'><a target=\'_blank\' href=\'' + aLink[i] + '\'>' + aVenueName[i] + '</a>' + aIntro[i] + '<br />' + aDatePublished[i] + '</div></div><a target=\'_blank\' href=\'' + aLink[i] + '\' class=\'ticketsTM\'>Find Tickets &gt;&gt;</a></div><br style=\'clear: both;\'/></div></div></div>',
                        position: {
                            corner: {
                                tooltip: 'bottomLeft',
                                target: 'topMiddle'
                            }
                        },
                        show: 'mouseover',
                        hide: 'mouseout',
                        style: {
                            width: 400,
                            padding: 0,
                            tip: true,
                            border: {
                                radius: 3,
                                color: '#004477'
                            }
                        
                        },
                        show: {
                            effect: {
                                length: 0
                            }
                        },
                        hide: {
                            effect: {
                                length: 0
                            },
                            fixed: true
                        }
                    })
                }
                
            }
            else {
                $("body").unhighlight({
                    element: 'a',
                    className: idCSS,
                    wordsOnly: true
                });
            }
        } 
        catch (e) {
            //console.log("error");
        }
        
    });
}


function tagLoaded(tagName){
    var resp = tagMap[tagName];
    if ((resp == "undefined") || (resp == undefined)) 
        return false;
    else 
        return true;
}

function loadRSSResponse(resp){
    if (jQuery.url.attr("host").indexOf("ticketmaster") >= 0) {
        numArticles = 0;
        return;
    }
    
    try {
        var idCSS;
        numArticles = 0;
        var start = new Date().getTime();
        var i = 0, limit = resp.response.docs.length, busy = false;
        if (limit != 0) {       
            var processor = setInterval(function(){
                if (!busy) {
                    busy = true;
                    if (resp.response.docs.length > 0) 
                        process(resp.response.docs[i]);
                    
                    if (++i == limit) {
                        clearInterval(processor);
                    }
                    
                    busy = false;
                }
                
            }, 100);
        }
    } 
    catch (e) {
        //alert("error:" + e.message + "]");
    }
}

function process(Event){
    for (var j = 0; j < Event.AttractionName.length; j++) {
        var Tag = Event.AttractionName[j];
        if (tagLoaded(Tag) == false) {
            //console.log(Tag);
            var Title = Event.EventName;
            var Artist = Tag;
            var Link = "http://www.ticketmaster.co.uk" + Event.AttractionSEOLink;
            var Intro = Event.VenueCityState;
			var Image = "http://media.ticketmaster.co.uk/en-gb" + Event.AttractionImage;
			
            var DatePublished = parseHour(Event.LocalEventDateDisplay);
            var LocalEventShortMonth = Event.LocalEventShortMonth;
            var LocalEventDay = Event.LocalEventDay;
            var LocalEventShortWeekday = Event.LocalEventShortWeekday;
            var VenueName = Event.VenueName;
            
            tagMap[Tag] = "1";
            
            aTag[numArticles] = Artist;
            aTitle[numArticles] = Title;
            aArtist[numArticles] = Artist;
            aDatePublished[numArticles] = DatePublished;
            aLink[numArticles] = Link;
            aIntro[numArticles] = Intro;
            aImage[numArticles] = Image;
            aLocalEventShortMonth[numArticles] = LocalEventShortMonth;
            aLocalEventDay[numArticles] = LocalEventDay;
            aLocalEventShortWeekday[numArticles] = LocalEventShortWeekday;
            aDatePublished[numArticles] = DatePublished;
            aVenueName[numArticles] = VenueName;
            
            
            idCSS = 'jQueryLinkTM' + numArticles;
            if ($('body a.' + idCSS).size() == 0) {
                if (!isLoaded) {
                    $("body").highlight(Tag, {
                        element: 'a',
                        className: idCSS,
                        wordsOnly: true
                    });
                }
                
                $("." + idCSS).css({
                    backgroundColor: "#004477",
                    color: "#ffffff",
                    padding: "0 25px 0 2px",
                    backgroundImage: "url(http://gce-tm.googlecode.com/svn/trunk/icon.png)",
                    backgroundRepeat: "no-repeat",
                    backgroundPosition: "right center"
                });
                
                $('body a.' + idCSS).qtipTM({
                    content: '<h1 class=\'logoTM\'><img src=\'http://gce-tm.googlecode.com/svn/trunk/img/logo-ticket.gif\' alt=\'TicketMaster\'/></h1><div class=\'contenidosTM\'><div class=\'izq\'><div class=\'dch\'><img src=\'' + Image + '\' alt=\'\' width=\'95\' height=\'60\' border=\'0\' class=\'mainTM\'/><div class=\'bloqueTM\'><span class=\'antetitulo\'>' + Artist + '</span><span class=\'titulo\'>' + Title + '</span><div class=\'eventoTM\'><span class=\'h6\'>Next Event</span><div class=\'fecha\'>-' + LocalEventShortMonth + '-<br /><span class=\'num\'>' + LocalEventDay + '</span><br /><strong>' + LocalEventShortWeekday + '</strong></div><div class=\'lugarTM\'><a target=\'_blank\' href=\'' + Link + '\'>' + VenueName + '</a>' + Intro + '<br />' + DatePublished + '</div></div><a target=\'_blank\' href=\'' + Link + '\' class=\'ticketsTM\'>Find Tickets &gt;&gt;</a></div><br style=\'clear: both;\'/></div></div></div>',
                    position: {
                        corner: {
                            tooltip: 'bottomLeft',
                            target: 'topMiddle'
                        }
                    },
                    show: 'mouseover',
                    hide: 'mouseout',
                    style: {
                        width: 400,
                        padding: 0,
                        tip: true,
                        border: {
                            radius: 3,
                            color: '#004477'
                        }
                    
                    },
                    show: {
                        effect: {
                            length: 0
                        }
                    },
                    hide: {
                        effect: {
                            length: 0
                        },
                        fixed: true
                    }
                })
                
                numArticles++;
            }
            
            
        }
    }
}


function loadTags(){
    chrome.extension.sendRequest({
        getData: "rss"
    }, function(response){
        respRss = response.rssData;
        loadRSSResponse(respRss);
    });
}

function parseDate(s){
    var date = null;
    date = new Date(parseInt(s.replace("/Date(", "").replace(")/", ""), 10));
    return date.toUTCString();
}

function parseHour(s){
    var myregexp = /(\d{2}:\d{2})/;
    var result;
    var match = myregexp.exec(s);
    if (match != null) {
        result = match[1];
    }
    else {
        result = "";
    }
    return result;
}


extension.onConnect.addListener(function(port){
    listenToState(port);
});
